package com.lhd.interceptor;

import cn.hutool.core.util.StrUtil;
import com.lhd.component.RedisComponent;
import com.lhd.entity.constants.Constants;
import com.lhd.exception.BusinessException;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: liuhd
 * @Date: 2025/3/24 15:05
 * @Description:  登录鉴权拦截器
 */

@Component
public class Interceptor implements HandlerInterceptor {
    @Resource
    private RedisComponent redisComponent;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            return true;
        }

        // 在请求处理之前进行调用（Controller方法调用之前）
        String token = request.getHeader(Constants.AUTHORIZATION);
        if (StrUtil.isBlank(token)){
            throw new BusinessException("用户未登录或登录已经过期，请重新登录");
        }
        if (redisComponent.getUserInfoDto(token) == null){
            throw new BusinessException("登录已经过期，请重新登录");
        }
        return true; // 如果返回false，则请求不会继续下去
    }
}
